package com.woniuxy.auth.controller;

import com.woniuxy.common.dto.AuthDto;
import com.woniuxy.common.entity.Account;
import com.woniuxy.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/10 0010-上午 10:38
 */
@RestController
public class AuthController {
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/login")
    public AuthDto login(Account account){
        //假设认证成功
        //生成token，refreshtoken
        String refreshToken = UUID.randomUUID().toString();
        String token = JwtUtil.createToken(account.getUname());
        //将token，refreshToken存放到redis
        Map map = new HashMap();
        map.put("token",token);
        map.put("uname",account.getUname());
        redisTemplate.opsForHash().putAll(refreshToken,map);
        //设置过期时间
        redisTemplate.expire(refreshToken, JwtUtil.REFRESH_TOKEN_EXPRE_TIME, TimeUnit.MILLISECONDS);
        // 将token、refreshtoken返回给浏览器
        AuthDto authDto = new AuthDto().setCode(200).setMessage("认证成功").setRefreshToken(refreshToken).setToken(token);
        return authDto;

    }

    /**
     * 刷新token
     * @param refreshToken
     * @return
     */
    public AuthDto refresh(String refreshToken){
        Map data = redisTemplate.opsForHash().entries(refreshToken);
        String uname = (String) data.get("uname");
        //生成新的token
        String token = JwtUtil.createToken(uname);
        //将新的token放回redis
        Map map = new HashMap();
        map.put("uname",uname);
        map.put("token",token);
        redisTemplate.opsForHash().putAll(refreshToken,map);
        return new AuthDto().setCode(200).setMessage("刷新成功").setToken(token).setRefreshToken(refreshToken);

    }

    /**
     * 验证角色的方法
     * @param refreshToken
     * @param role
     * @return
     */
    @PostMapping("/hasRole/{refreshToken}/{role}")
    public boolean hasRole(@PathVariable("refreshToken") String refreshToken, @PathVariable("role") String role){
        //通过refreshToken去redis中插叙当前用户
        Map data =  redisTemplate.opsForHash().entries(refreshToken);
        String uname = (String)data.get("uname");
        //拿用户名去数据库查询当前用户的所有角色
        List<String> roles = Arrays.asList("admin","teacher");
        if(roles.contains(role)){
            return true;
        }
        return false;

    }

}
